﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;

/// <summary>
/// Author:
/// Created Date:10-Feb-2011
/// Description:Used to Read and Update the XML Data.
/// </summary>
namespace EncircleFTM
{
    public partial class frmSettings : Form
    {
        #region "Member variables"
        private bool isSettingsSaved = false;
        //private Thread thread = null;
        #endregion
        #region "Methods and Events"
        /// <summary>
        /// Default constructor
        /// </summary>   
        public frmSettings()
        {
            InitializeComponent();
        }

        [DllImport("User32.dll")]
        public static extern Int32 SetForegroundWindow(int hWnd);
        [DllImport("user32.dll")]
        public static extern int FindWindow(string lpClassName, string lpWindowName);
        private void BringToFront(string className, string CaptionName)
        {
            SetForegroundWindow(FindWindow(className, CaptionName));
        }

        /// <summary>
        /// To Populate the Values.
        /// </summary>
        public void PopulateSettings()
        {
            try
            {
                txtCompanyName.Text = clsSettings.CompanyName;
                txtUniqueID.Text = clsSettings.UniqueID;
                txtURL.Text = clsSettings.URL;
                txtUploadServiceURL.Text = clsSettings.UploadURL;
                txtFolderPath.Text = clsSettings.FolderPath;
                bool IsAdditionalInfo = false;
                if (clsSettings.ISAdditionalInfo != string.Empty)
                {
                    IsAdditionalInfo = Convert.ToBoolean(clsSettings.ISAdditionalInfo);
                }
                chkAdditionalInfo.Checked = IsAdditionalInfo;
                cmbClrLogSchedule.SelectedItem = clsSettings.objClearLogSchedule.ToString();
                this.LostFocus += new EventHandler(frmSettings_LostFocus);
                this.Shown += new EventHandler(frmSettings_Shown);
            }
            catch (Exception ex)
            {
                clsCommonData.WriteError(ex.ToString());
            }
            txtCompanyName.Focus();
        }

        /// <summary>
        /// Used to hamdle lost focus event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void frmSettings_LostFocus(object sender, EventArgs e)
        {

            this.BringToFront();

        }

        void frmSettings_Shown(object sender, EventArgs e)
        {
            this.TopMost = true;
            this.BringToFront();
        }

        /// <summary>
        /// To Populate the Values when Loading.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Encirclesettings_Load(object sender, EventArgs e)
        {
            try
            {
                //Load Clear Schedule dropdown control
                cmbClrLogSchedule.Items.Add(clsCommonData.ClearLogSchedule.None.ToString());
                cmbClrLogSchedule.Items.Add(clsCommonData.ClearLogSchedule.EveryDay.ToString());
                cmbClrLogSchedule.Items.Add(clsCommonData.ClearLogSchedule.EveryWeek.ToString());
                cmbClrLogSchedule.Items.Add(clsCommonData.ClearLogSchedule.EveryMonth.ToString());
                cmbClrLogSchedule.Items.Add(clsCommonData.ClearLogSchedule.EveryQuarter.ToString());
                cmbClrLogSchedule.Items.Add(clsCommonData.ClearLogSchedule.EveryHalfyear.ToString());
                cmbClrLogSchedule.Items.Add(clsCommonData.ClearLogSchedule.EveryYear.ToString());
                cmbClrLogSchedule.SelectedIndex = 0;

                PopulateSettings();
            }
            catch (Exception ex)
            {
                clsCommonData.WriteError(ex.ToString());
            }
        }

        /// <summary>
        /// To Update the XML Data.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                clsCommonData.ClearLogSchedule clrLogSch = (clsCommonData.ClearLogSchedule)Enum.Parse(typeof(clsCommonData.ClearLogSchedule), cmbClrLogSchedule.Text);

                if (clsSettings.UpdateSettings(txtCompanyName.Text, txtUniqueID.Text, txtURL.Text, txtUploadServiceURL.Text, txtFolderPath.Text, clrLogSch, chkAdditionalInfo.Checked))
                {
                    MessageBox.Show(clsCommonData.MSG_SUCCESS, clsCommonData.STR_APPNAME, MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                    clsCommonData.StopScheduler();
                    clsSettings.ReadSettings();
                    PopulateSettings();
                    clsCommonData.StartScheduler();
                    isSettingsSaved = true;
                    this.Close();
                }
                else
                {
                    MessageBox.Show(clsCommonData.MSG_UPDATE_FAILURE, clsCommonData.STR_APPNAME, MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                }
            }
            catch (Exception ex)
            {
                clsCommonData.WriteError(ex.ToString());
            }
        }

        /// <summary>
        /// To show the folder Browse Dialog to choose the FolderPath.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            try
            {
                this.TopMost = false;
                string FolderName = ChooseWatchingFolder(txtFolderPath.Text.Trim());
                if (FolderName.Trim().Length > 0)
                    txtFolderPath.Text = FolderName;
            }
            catch (Exception ex)
            {
                clsCommonData.WriteError(ex.ToString());
            }
        }

        /// <summary>
        /// Gets the folder in Sta Thread
        /// </summary>
        /// <returns>The path to the selected folder or (if nothing selected) the empty value</returns>
        private string ChooseWatchingFolder(string selFolder)
        {
            var result = new StringBuilder();
            var thread = new Thread(obj =>
            {
                var builder = (StringBuilder)obj;
                using (var dialog = new FolderBrowserDialog())
                {

                    dialog.RootFolder = Environment.SpecialFolder.MyComputer;
                    if (selFolder.Trim().Length > 0) dialog.SelectedPath = selFolder;
                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                        builder.Append(dialog.SelectedPath);
                    }
                }
            });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start(result);

            while (thread.IsAlive)
            {
                Thread.Sleep(1);
            }
            return result.ToString();
        }

        /// <summary>
        /// To close the Settings Form.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                isSettingsSaved = false;
                this.Dispose();
            }
            catch (Exception ex)
            {
                clsCommonData.WriteError(ex.ToString());
            }
        }

        /// <summary>
        /// Used to handle settings close and dialog result
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            switch (isSettingsSaved)
            {
                case true:
                    this.DialogResult = DialogResult.OK;
                    break;
                case false:
                    this.DialogResult = DialogResult.Cancel;
                    break;
                default:
                    this.DialogResult = DialogResult.Cancel;
                    break;
            }

        }

        #endregion
    }
}
